<?php

namespace App\Service;

use App\Models\CommodityOrder;
use App\Models\GroupBuy;

class GroupBuyService
{
    public static function joinById($id, $userId, $oderId)
    {
        $group = GroupBuy::lockForUpdate()->find($id);
        if (!$group) {
            return false;
        }
        // 如果满团
        if ($group->total_number - $group->join_number <= 0) {
            return false;
        }

        $orderArr = explode(',', $group->order_ids);
        array_push($orderArr, $oderId);
        $userArr = explode(',', $group->user_ids);
        array_push($userArr, $userId);

        $group->join_number += 1;
        $group->order_ids = implode(',', $orderArr);
        $group->user_ids = implode(',', $userArr);
        // 修改拼团数据表
        if ($group->save()) {
            $flag = $group->join_number == $group->total_number;
            // 如果现在拼团人数足够，就要修改订单表
            $flag && $updateResult = self::updateOrder($orderArr);

            if (isset($updateResult)) {
                return $updateResult ? true : false;
            }
            return true;
        }
    }

    public static function updateOrder($orderIds)
    {
        $result = CommodityOrder::whereIn('id', $orderIds)->update(['group_buy_status' => 1]);
        if ($result) {
            return true;
        } else {
            return false;
        }
    }

    public static function open($params)
    {
        list($userIds, $orderIds, $spuId, $totalNumber) = $params;

        $userIdsJson = $userIds;
        $orderIdsJson = $orderIds;

        $params = [
            'order_ids' => $orderIdsJson,
            'user_ids' => $userIdsJson,
            'spu_id' => $spuId,
            'total_number' => $totalNumber
        ];
        $result = GroupBuy::create($params);
        if ($result) {
            return true;
        } else {
            return false;
        }
    }
}
